package com.wgzx.modbus.entity.request;

import com.wgzx.modbus.entity.ModbusReq;
import io.netty.buffer.ByteBuf;

import static com.wgzx.modbus.constant.FunctionCode.WRITE_MULTIPLE_REGISTERS;
import static com.wgzx.modbus.util.ModbusUtil.validateRange;

/**
 * 写多个寄存器 <br/>
 * 功能码：0x10 <br/>
 * 起始地址：2个字节0x0000至0xFFFF <br/>
 * 寄存器数量：2个字节0x0001至0x007B <br/>
 * 字节数：1个字节 <br/>
 * 寄存器值：N个字节 <br/>
 *
 * @author gexin
 */
public class WriteMultipleRegistersRequest extends ModbusReq {

    private short byteCount;
    private int[] registers;

    public WriteMultipleRegistersRequest(int startingAddress, int[] registers) {
        super(WRITE_MULTIPLE_REGISTERS, startingAddress, registers.length);
        validateRange(startingAddress, "startingAddress", 0x0000, 0xFFFF);
        validateRange(startingAddress, "registers.length", 0x00, 0x007B);

        this.byteCount = (short) (registers.length * 2);
        this.registers = registers;
    }

    @Override
    public int calculateLength() {
        return super.calculateLength() + 1 + byteCount;
    }

    @Override
    public void encode(ByteBuf buffer) {
        super.encode(buffer);
        buffer.writeByte(byteCount);
        for (int register : registers) {
            buffer.writeShort(register);
        }
    }

    @Override
    public String toString() {
        StringBuilder registersStr = new StringBuilder();
        registersStr.append("{");
        for (int i = 0; i < registers.length; i++) {
            registersStr.append("register_");
            registersStr.append(i);
            registersStr.append("=");
            registersStr.append(registers[i]);
            registersStr.append(", ");
        }
        registersStr.delete(registersStr.length() - 2, registersStr.length());
        registersStr.append("}");

        return "WriteMultipleRegistersRequest{" + "startingAddress=" + address + ", quantityOfRegisters=" + value + ", byteCount=" + byteCount + ", registers=" + registersStr + '}';
    }
}
